import React, { createContext, useReducer } from "react";
import type { accountStateType, accountReducerType, contextType } from "./../../types/accountType"


const initialState: accountStateType = {
    prames: {
        username: undefined,
        phone: undefined,
        account: undefined,
    },
    data:{
        count:0,
        list:[]
    },
    addOrEdit:false,
    type:"add",
    user:{
        userId:0,
        account:""
    },
};


const reducer = (state: accountStateType, action: accountReducerType): accountStateType => {
    console.log(action)
    switch (action.type) {
        case 'SET_PRAMES': return { ...state, prames: state.prames = action.payLoad };
        case 'CLEAR_PRAMES': return { ...state, prames: state.prames = initialState.prames };
        case 'SET_RESDATA': return { ...state, data: state.data = action.payLoad };
        case 'CHANGE_ADDOREDIT': return { ...state, addOrEdit: state.addOrEdit = action.payLoad };
        case 'SET_ID': return { ...state, user: state.user = action.payLoad };
        case 'SET_TYPE': return { ...state, type: state.type = action.payLoad };
        default: throw new Error('Unexpected action');
    }
};

export const AccountContext = createContext<contextType>({} as contextType);

const AccountContextProvider: React.FC<React.PropsWithChildren> = ({ children }) => {
    const [state, dispatch] = useReducer(reducer, initialState);
    return (<AccountContext.Provider value={{ state, dispatch }}>{children}</AccountContext.Provider>)
}

export default AccountContextProvider;